package com.sprite.framework.entity.idgenerator;

import com.sprite.framework.entity.Delegator;
import com.sprite.framework.entity.EntityScriptExecutor;
import com.sprite.framework.entity.IdGenerator;
import com.sprite.framework.entity.util.SequenceUtil;
import com.sprite.utils.cache.UtilCache;

/**
 * 自增序列生成器
 * <p>缺点：可能会出现跳步</p>
 * @author Jack
 */
public class SequenceGenerator implements IdGenerator{
	private UtilCache<SequenceUtil> sequenceCached = UtilCache.createUtilCache("cache.SequenceUtil");

	private EntityScriptExecutor scriptExecutor;
	
	private Delegator delegator;
	
	
	public SequenceGenerator(EntityScriptExecutor scriptExecutor, Delegator delegator) {
		super();
		this.scriptExecutor = scriptExecutor;
		this.delegator = delegator;
	}

	@Override
	public String name() {
		return "sequence";
	}

	@Override
	public String nextId(String entityName) {
		SequenceUtil sequenceUtil = sequenceCached.get(entityName);
		if(sequenceUtil == null){
			synchronized (sequenceCached) {
				if(sequenceUtil == null){
					sequenceUtil = new SequenceUtil(entityName,1000,100, scriptExecutor, delegator);
					sequenceCached.put(entityName, sequenceUtil);
				}
			}
		}

		return sequenceUtil.nextValue()+"";
	}

	public EntityScriptExecutor getScriptExecutor() {
		return scriptExecutor;
	}

	public void setScriptExecutor(EntityScriptExecutor scriptExecutor) {
		this.scriptExecutor = scriptExecutor;
	}

	public Delegator getDelegator() {
		return delegator;
	}

	public void setDelegator(Delegator delegator) {
		this.delegator = delegator;
	}

}
